package com.wyix;


import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/**
 * @author wangdx
 * @since 2025/8/5
 */
public class HttpClientGetExample {

    public static void main(String[] args) throws Exception {
        // 1. 创建HttpClient（可配置连接池、超时等）
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(5)) // 连接超时
                .build();

        // 2. 创建HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                .timeout(Duration.ofSeconds(5)) // 响应超时
                .header("Accept", "application/json")
                .GET() // GET请求
                .build();

        // 3. 发送请求并获取响应
        HttpResponse<String> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofString() // 响应体转为String
        );

        // 4. 处理响应
        System.out.println("状态码: " + response.statusCode());
        System.out.println("响应体: " + response.body());
    }
}
